package com.clear.auth.application.controller;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson.JSON;
import com.clear.auth.application.convert.AuthUserDTOConverter;
import com.clear.auth.domain.entity.AuthUserBO;
import com.clear.auth.domain.redis.RedisUtil;
import com.clear.auth.domain.service.AuthUserDomainService;
import com.clear.auth.entity.AuthUserDTO;
import com.clear.auth.entity.Result;
import com.google.common.base.Preconditions;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Objects;

@RestController
@RequestMapping("/user/")
@Slf4j
public class UserController {

    @Resource
    private AuthUserDomainService authUserDomainService;

    @Resource
    private RedisUtil redisUtil;

    /**
     * 用户注册
     *
     * @param authUserDTO
     * @return
     */
    @PostMapping("register")
    public Result<Boolean> register(@RequestBody AuthUserDTO authUserDTO) {
        try {
            if (log.isInfoEnabled()) {
                log.info("UserController.register.dto:{}", JSON.toJSONString(authUserDTO));
            }
            Preconditions.checkArgument(!StringUtils.isBlank(authUserDTO.getUserName()), "用户名不能为空");
            Preconditions.checkArgument(!StringUtils.isBlank(authUserDTO.getEmail()), "邮件地址不能为空");
            Preconditions.checkArgument(!StringUtils.isBlank(authUserDTO.getPassword()), "密码不能为空");

            AuthUserBO authUserBO = AuthUserDTOConverter.INSTANCE.convertDTOToBO(authUserDTO);

            boolean result = authUserDomainService.register(authUserBO);
            return Result.ok(result);
        } catch (Exception e) {
            log.error("UserController.register.error:{}", e.getMessage(), e);
            return Result.fail("注册用户失败");
        }
    }

    /**
     * 更新用户信息
     *
     * @param authUserDTO
     * @return
     */
    @PostMapping("update")
    public Result<Boolean> update(@RequestBody AuthUserDTO authUserDTO) {
        try {
            if (log.isInfoEnabled()) {
                log.info("UserController.update.dto:{}", JSON.toJSONString(authUserDTO));
            }
            Preconditions.checkArgument(Objects.nonNull(authUserDTO), "参数不能为空！");
            Preconditions.checkArgument(!StringUtils.isBlank(authUserDTO.getUserName()), "用户名不能为空");

            AuthUserBO authUserBO = AuthUserDTOConverter.INSTANCE.convertDTOToBO(authUserDTO);

            boolean result = authUserDomainService.update(authUserBO);
            return Result.ok(result);
        } catch (Exception e) {
            log.error("UserController.update.error:{}", e.getMessage(), e);
            return Result.fail("更新用户信息失败");
        }
    }

    /**
     * 查看用户信息
     *
     * @param authUserDTO
     * @return
     */
    @PostMapping("getUserInfo")
    public Result<AuthUserDTO> getUserInfo(@RequestBody AuthUserDTO authUserDTO) {
        try {
            if (log.isInfoEnabled()) {
                log.info("UserController.getUserInfo.dto:{}", JSON.toJSONString(authUserDTO));
            }
            Preconditions.checkArgument(StringUtils.isNotBlank(authUserDTO.getUserName()), "用户名称（openId）不能为空");

            AuthUserBO authUserBO = AuthUserDTOConverter.INSTANCE.convertDTOToBO(authUserDTO);

            AuthUserBO userInfoBO = authUserDomainService.getUserInfo(authUserBO);
            AuthUserDTO userInfoDTO = AuthUserDTOConverter.INSTANCE.convertBOToDTO(userInfoBO);
            return Result.ok(userInfoDTO);
        } catch (Exception e) {
            log.error("UserController.getUserInfo.error:{}", e.getMessage(), e);
            return Result.fail("查看用户信息失败");
        }
    }

    /**
     * 删除用户
     *
     * @param authUserDTO
     * @return
     */
    @PostMapping("delete")
    public Result<Boolean> delete(@RequestBody AuthUserDTO authUserDTO) {
        try {
            if (log.isInfoEnabled()) {
                log.info("UserController.delete.dto:{}", JSON.toJSONString(authUserDTO));
            }
            Preconditions.checkNotNull(authUserDTO.getId(), "用户id不能为空");

            AuthUserBO authUserBO = AuthUserDTOConverter.INSTANCE.convertDTOToBO(authUserDTO);

            // 逻辑删除
            boolean result = authUserDomainService.delete(authUserBO);
            return Result.ok(result);
        } catch (Exception e) {
            log.error("UserController.delete.error:{}", e.getMessage(), e);
            return Result.fail("删除用户失败");
        }
    }


    /**
     * 用户启用/禁用
     *
     * @param authUserDTO
     * @return
     */
    @PostMapping("changeStatus")
    public Result<Boolean> changeStatus(@RequestBody AuthUserDTO authUserDTO) {
        try {
            if (log.isInfoEnabled()) {
                log.info("UserController.changeStatus.dto:{}", JSON.toJSONString(authUserDTO));
            }
            Preconditions.checkNotNull(authUserDTO.getId(), "用户id不能为空");
            Preconditions.checkNotNull(authUserDTO.getStatus(), "用户状态不能为空");

            AuthUserBO authUserBO = AuthUserDTOConverter.INSTANCE.convertDTOToBO(authUserDTO);

            boolean result = authUserDomainService.changeStatus(authUserBO);
            return Result.ok(result);
        } catch (Exception e) {
            log.error("UserController.changeStatus.error:{}", e.getMessage(), e);
            return Result.fail("用户状态更新操作失败");
        }
    }


    /**
     * 用户登录
     *
     * @param verificationCode 验证码
     * @return
     */
    @RequestMapping("doLogin")
    public Result<SaTokenInfo> doLogin(@RequestParam("validCode") String verificationCode) {
        try {
            log.info("UserController.doLogin.param:{}", verificationCode);
            Preconditions.checkArgument(!StringUtils.isBlank(verificationCode), "验证码不能为空");

            SaTokenInfo saTokenInfo = authUserDomainService.doLogin(verificationCode);
            if (log.isInfoEnabled()){
                log.info("UserController.doLogin.saTokenInfo:{}", JSON.toJSONString(saTokenInfo));
            }
            return Result.ok(saTokenInfo);
        } catch (Exception e) {
            log.error("UserController.doLogin.error:{}", e.getMessage(), e);
            return Result.fail("用户登录操作失败");
        }
    }


    // 查询登录状态，浏览器访问： http://localhost:8081/user/isLogin
    @RequestMapping("isLogin")
    public String isLogin() {
        return "当前会话是否登录：" + StpUtil.isLogin();
    }

    /**
     * 用户退出
     *
     * @param username 用户名 openId
     * @return
     */
    @RequestMapping("logOut")
    public Result logout(@RequestParam("userName") String username) {
        try {
            log.info("UserController.logout.username:{}", username);
            Preconditions.checkArgument(!StringUtils.isBlank(username), "用户名不能为空");

            StpUtil.logout(username);

            return Result.ok();
        } catch (Exception e) {
            log.error("UserController.doLogin.error:{}", e.getMessage(), e);
            return Result.fail("用户退出失败");
        }
    }

}
